package aliyun.cx.admin.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * 图片代理控制器
 * 用于代理外部图片请求，绕过防盗链限制
 */
@RestController
@RequestMapping("/api/proxy")
@CrossOrigin(origins = "*", maxAge = 3600)
public class ImageProxyController {
    
    /**
     * 代理图片请求
     */
    @GetMapping("/image")
    public ResponseEntity<byte[]> proxyImage(@RequestParam("url") String imageUrl) {
        try {
            // 创建URL连接
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            
            // 设置请求头，模拟浏览器请求
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36");
            
            // 根据图片来源设置不同的Referer
            String referer = getRefererForUrl(imageUrl);
            connection.setRequestProperty("Referer", referer);
            
            connection.setRequestProperty("Accept", "image/webp,image/apng,image/*,*/*;q=0.8");
            connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
            connection.setRequestProperty("Cache-Control", "no-cache");
            connection.setRequestProperty("Sec-Fetch-Dest", "image");
            connection.setRequestProperty("Sec-Fetch-Mode", "no-cors");
            connection.setRequestProperty("Sec-Fetch-Site", "cross-site");
            
            // 设置连接超时
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(10000);
            
            // 获取响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 读取图片数据
                InputStream inputStream = connection.getInputStream();
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                
                byte[] imageData = outputStream.toByteArray();
                
                // 获取Content-Type
                String contentType = connection.getContentType();
                if (contentType == null || contentType.isEmpty()) {
                    contentType = "image/jpeg"; // 默认类型
                }
                
                // 设置响应头
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.parseMediaType(contentType));
                headers.setContentLength(imageData.length);
                headers.setCacheControl("public, max-age=3600"); // 缓存1小时
                
                inputStream.close();
                outputStream.close();
                connection.disconnect();
                
                return new ResponseEntity<>(imageData, headers, HttpStatus.OK);
            } else {
                connection.disconnect();
                return new ResponseEntity<>(HttpStatus.NOT_FOUND);
            }
            
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    
    /**
     * 检查图片是否可访问
     */
    @GetMapping("/check")
    public ResponseEntity<Map<String, Object>> checkImage(@RequestParam("url") String imageUrl) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            
            // 设置请求头
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36");
            
            // 根据图片来源设置不同的Referer
            String referer = getRefererForUrl(imageUrl);
            connection.setRequestProperty("Referer", referer);
            
            connection.setRequestMethod("HEAD");
            
            int responseCode = connection.getResponseCode();
            connection.disconnect();
            
            if (responseCode == HttpURLConnection.HTTP_OK) {
                result.put("code", 200);
                result.put("status", "success");
                result.put("message", "图片可访问");
            } else {
                result.put("code", responseCode);
                result.put("status", "error");
                result.put("message", "图片不可访问，状态码: " + responseCode);
            }
            
        } catch (IOException e) {
            result.put("code", 500);
            result.put("status", "error");
            result.put("message", "检查失败: " + e.getMessage());
        }
        
        return ResponseEntity.ok(result);
    }
    
    /**
     * 根据图片URL智能设置Referer
     */
    private String getRefererForUrl(String imageUrl) {
        if (imageUrl.contains("baidu.com") || imageUrl.contains("bcebos.com")) {
            return "https://www.baidu.com";
        } else if (imageUrl.contains("xhscdn.com") || imageUrl.contains("xiaohongshu.com")) {
            return "https://www.xiaohongshu.com";
        } else if (imageUrl.contains("qq.com")) {
            return "https://www.qq.com";
        } else if (imageUrl.contains("weibo.com")) {
            return "https://www.weibo.com";
        } else if (imageUrl.contains("douyin.com") || imageUrl.contains("bytedance.com")) {
            return "https://www.douyin.com";
        } else if (imageUrl.contains("bilibili.com")) {
            return "https://www.bilibili.com";
        } else if (imageUrl.contains("zhihu.com")) {
            return "https://www.zhihu.com";
        } else {
            // 默认使用图片所在域名作为Referer
            try {
                URL url = new URL(imageUrl);
                return url.getProtocol() + "://" + url.getHost();
            } catch (Exception e) {
                return "https://www.google.com";
            }
        }
    }
}
